<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Level 1</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="./js/d3.v6.js"></script>
    <script type="text/javascript" src="./js/jquery.min.js"></script>
    <style>
        .inline_block{
            display: inline-block;
        }
        .ibutton{
            width: 130px;
            height: 40px;
            margin: 10px;
        }
        .heatmap{
            width:1200px;
            height:800px;
        }
    </style>
</head>
<body>
    <div>
        <button class='ibutton' id='buttonMax'>Max</button>
        <button class='ibutton' id='buttonMin'>Min</button>
    </div>
    <div>
        <div id="heatmap" class='heatmap'></div>
    </div>

</body>
<script>
    $(function(){
        var margin = { top: 100, right: 50, bottom: 80, left: 100 },
            width = 1000 - margin.left - margin.right,
            height = 600 - margin.top - margin.bottom,
            gridHeight = height / 12, // there are 12 months in a year
            gridMargin = { top: 3, right: 3, bottom: 3, left: 3 },
            legendSize = { height: 20, width: 600}
            months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec"];
        
        var svg = d3.select("#heatmap").append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
        
        var xScale = d3.scaleLinear();
        var yScale = d3.scalePoint();
        var colorScale = d3.scaleLinear();

        var color = d3.scaleSequential(d3.interpolateRdBu);

        // create tooltip
        var tooltip = d3.select("body")
            .append("div")
            .style("position", "absolute")
            .style("background-color", "snow")
            .style("padding", "2px")
            .style("z-index", "1")
            .style("visibility", "hidden")
            .text("a simple tooltip");
        // create title
        var title = svg.append("text")
            .attr("x", (width + margin.left + margin.right) / 2)             
            .attr("y", (margin.top / 2))
            .attr("text-anchor", "middle")  
            .style("font-size", "24px")
            .text(" Maximum Monthly Temperature of Hong Kong");
        
        // create chart
        var g = svg.append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
        

        var defs = svg.append("defs");
        defs.append("linearGradient")
            .attr("id", "linear-gradient")
            .selectAll("stop")
            .data(color.ticks().reverse().map((t, i, n) => {
                //console.log(t)
                return { offset: i/n.length, color: color(t) }
            } ))
            .enter().append("stop")
            .attr("offset", d => d.offset)
            .attr("stop-color", d => d.color);
        var legend = g.append('g')
            .attr("transform", "translate(0," + (height + 20 + legendSize.height) + ")")
        legend.append("rect")
            .attr("width", legendSize.width)
            .attr("height", legendSize.height)
            .style("fill", "url(#linear-gradient)");

        var grids;
        d3.csv('./data/temperature_daily.csv').then(function(data){
             //增广数据 便于后续数据处理
            var parseDate = d3.timeParse('%Y-%m-%d');
            var formatDate = d3.timeFormat('%Y-%m');
            data.forEach(function(e){
                var date = parseDate(e.date);
                e.year = date.getFullYear();
                e.month=months[date.getMonth()];
                e.ym=formatDate(date); 
            })

            t=d3.rollup(data, v => {
                //return d3.max(v,e=>{return parseInt(e.max_temperature)})
                return {"month": v[0].month, 
                        "year": v[0].year,
                        "max":d3.max(v,e=>{return parseInt(e.max_temperature)}),
                        "min":d3.min(v,e=>{return parseInt(e.max_temperature)})
                        };
            }, d => d.ym)
            dataArray=[]
            //console.log(t)
            t.forEach(e=>{dataArray.push(e)})
            //console.log(dataArray[1])
            data=dataArray;
            
            var xRange = d3.extent(data.map(e => e.year));
            var minTemp = d3.min(data.map(e => e.min));
            var maxTemp = d3.max(data.map(e => e.max));
            var gridWidth = width / (xRange[1] - xRange[0] + 1);
            var minTemp = d3.min(data.map(e => e.min));
            var maxTemp = d3.max(data.map(e => e.max));

            xScale.domain(xRange).range([gridWidth/8, width - gridWidth/8]);
            yScale.domain(months).range([gridHeight/8, height - gridHeight/8]);
            colorScale.domain([minTemp,maxTemp]).range([0,legendSize.width ]);
            //colorScale = d3.scaleLinear()
            //.domain([0, maxTemp*0.7, maxTemp])
            //.range(['#94c5de', '#fdae61', '#9e0142']);
            //console.log(color.domain())
            g.append("g")
            .attr("transform", "translate(16,0)")   
            .call(d3.axisTop(xScale).ticks(xRange[1] - xRange[0] + 1, d3.format("d")));

            g.append("g")
            .attr("transform", "translate(0,16)")
            .call(d3.axisLeft(yScale));
            grids = g.append("g")
            .attr("transform", "translate(16,16)")
            .selectAll("rect")
            .data(data)
            .enter().append("rect")
            .attr("x", d => xScale(d.year) - gridWidth / 2 + gridMargin.left)
            .attr("y", d => yScale(d.month) - gridHeight / 2 + gridMargin.top)
            .attr("width", gridWidth - gridMargin.left - gridMargin.right)
            .attr("height", gridHeight - gridMargin.top - gridMargin.bottom)
            .attr("fill", d => {
                //console.log(colorScale(100))
                
                //console.log(d.max)
                return color(1 - (d.max-minTemp)/(maxTemp-minTemp));
            })
            .on('mouseover', function(e,d) {
                tooltip.style("visibility", "visible")
                .text("Date: " + d.year+" "+d.month + " max: " + d.max);
            })
            .on("mousemove", function(event){
                return tooltip.style("top", (event.pageY-12)+"px").style("left",(event.pageX+12)+"px");})
            .on("mouseout", function(){return tooltip.style("visibility", "hidden");});
            
            //console.log(colorScale.domain())
            //var colorRange = d3.extent(colorScale.range.map(e => e.year));
    
            colorAxis = legend.append('g')
                .attr("transform", "translate(0," + legendSize.height + ")")
                .call(d3.axisBottom(colorScale));
            function showMax() {
                title.text("Maximum Monthly Temperature of Hong Kong");
                grids
                    .on('mouseover', function(e,d) {
                        tooltip.style("visibility", "visible")
                        .text("Date: " + d.year+" "+d.month + " max: " + d.max);
                    })
                    .transition().attr("fill", d => color(1 - (d.max-minTemp)/(maxTemp-minTemp)));
            }

            function showMin() {

                title.text("Minimum Monthly Temperature of Hong Kong");
                grids
                    .on('mouseover', function(e,d) {
                        tooltip.style("visibility", "visible")
                        .text("Date: " + d.year+" "+d.month + " min: " + d.min);
                    })
                    .transition().attr("fill", d => color(1 - (d.min-minTemp)/(maxTemp-minTemp)));
            }
            $('#buttonMax').on('click',showMax);
            $('#buttonMin').on('click',showMin);
            $('#heatmap').toggle(showMin,showMax);
        })








    })
</script>
</html>